package com.example.zp.jcenterupload.widget;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PagerTabScroller extends HorizontalScrollView {
	private int INVALID_POSITION = -1;
	private OnClickListenerTab mOnTabClickListener;
	private ViewPager mViewpager;
	private LinearLayout tabContainer;
	private int mCurScrollPosition = -1;
	private int mCacheWidth;
	private Paint mIndicatorPaint;
	private int mIndicatorHeight = 3;
	private int mCurrentPosition;
	private float mPositionOffset;
	private View mChild;
	private View mNextChild;
	private View mLastSelectTab;
	private int mSelectColor = 0xFF0ed41a;
	private int mDefaultColor = 0xFF484848;
	private boolean isClickTab = false;
	private boolean isInit = true;
	private float mDensity;
	private OnTabSelectListener mOnTabSelectListener;

	public interface OnTabSelectListener {
		void onTabSelect(int position);
	}

	public PagerTabScroller(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public PagerTabScroller(Context context, AttributeSet attrs) {
		// defStyle==0的时候没有显示滚动条 与方法 setHorizontalScrollBarEnabled(false)效果一样;
		this(context, attrs, 0);
	}

	public PagerTabScroller(Context context) {
		this(context, null);
	}

	@Override
	public void addView(View child) {
		if (getChildCount() > 0) {
			removeAllViews();
		}

		super.addView(child);
	}

	@Override
	public void addView(View child, int index) {
		if (getChildCount() > 0) {
			removeAllViews();
		}

		super.addView(child, index);
	}

	@Override
	public void addView(View child, ViewGroup.LayoutParams params) {
		if (getChildCount() > 0) {
			removeAllViews();
		}

		super.addView(child, params);
	}

	@Override
	public void addView(View child, int index, ViewGroup.LayoutParams params) {
		if (getChildCount() > 0) {
			removeAllViews();
		}

		super.addView(child, index, params);
	}

	private void init(Context context) {
		tabContainer = new LinearLayout(context);
		tabContainer.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
		tabContainer.setOrientation(LinearLayout.HORIZONTAL);
		addView(tabContainer, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		mIndicatorPaint = new Paint();
		mIndicatorPaint.setColor(mSelectColor);
		mIndicatorPaint.setAntiAlias(true);

		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display defaultDisplay = wm.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		defaultDisplay.getMetrics(outMetrics);
		mIndicatorHeight = (int) (3 * outMetrics.density);
		mDensity = outMetrics.density;
		setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
			@Override
			public void onChildViewRemoved(View parent, View child) {

			}
			@Override
			public void onChildViewAdded(View parent, View child) {
				if (mOnTabClickListener == null) {
					mOnTabClickListener = new OnClickListenerTab();
				}
				if (child instanceof LinearLayout) {
					int count = ((LinearLayout) child).getChildCount();
					for (int i = 0; i < count; i++) {
						View childAt = ((LinearLayout) child).getChildAt(i);
						childAt.setOnClickListener(mOnTabClickListener);
					}
				}
				if (mViewpager != null) {

				}
			}
		});

	}

	public void addTab(View tab) {
		if (mOnTabClickListener == null) {
			mOnTabClickListener = new OnClickListenerTab();
		}
		if (tab instanceof TextView) {
			TextView tv = (TextView) tab;
			int currentTextColor = tv.getCurrentTextColor();
			mDefaultColor = currentTextColor;
		}
		if (tabContainer != null) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
			params.gravity = Gravity.CENTER;
			int padding = (int) (10 * mDensity);
			tab.setPadding(padding, 0, padding, 0);
			tab.setOnClickListener(mOnTabClickListener);
			tabContainer.addView(tab, params);
		}
		// Log.e("PagerTabScroll", "addTab()");
	}

	public void addTextTab(String text,int textSize,int textColor){
		if (mOnTabClickListener == null) {
			mOnTabClickListener = new OnClickListenerTab();
		}
		TextView textView = new TextView(getContext());
		textView.setText(text);
		textView.setTextColor(textColor);
		textView.setTextSize(textSize);
		textView.setGravity(Gravity.CENTER);
		mDefaultColor = textColor;
		if (tabContainer != null) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
			params.gravity = Gravity.CENTER;
			int padding = (int) (20 * mDensity);
			textView.setPadding(padding, 0, padding, 0);
			textView.setOnClickListener(mOnTabClickListener);
			tabContainer.addView(textView, params);
		}
	}

	public void setTextAtPosition(String text,int position){
		if(tabContainer!=null&&tabContainer.getChildCount()>position){
			View child = tabContainer.getChildAt(position);
			if(child instanceof TextView){
				((TextView) child).setText(text);
			}
		}
	}

	public void setOnTabSelectListener(OnTabSelectListener listener) {
		mOnTabSelectListener = listener;
	}

	protected void onTabSelect(int position) {
		if (mOnTabSelectListener != null) {
			mOnTabSelectListener.onTabSelect(position);
		}
	}

	class OnClickListenerTab implements OnClickListener {
		@Override
		public void onClick(View v) {
			int position = getPositionForView(v);
			if (mViewpager != null) {
				try {
					if (isClickTab || (position == mCurrentPosition)) {
						return;
					}
					isClickTab = true;
					mViewpager.setCurrentItem(position);
				} catch (Exception e) {

				}
			}
		}
	}

	public int getTabCount() {
		if (tabContainer == null) {
			return 0;
		}
		return tabContainer.getChildCount();
	}

	public int getPositionForView(View view) {
		View listItem = view;
		try {
			View v;
			while (!(v = (View) listItem.getParent()).equals(tabContainer)) {
				listItem = v;
			}
		} catch (ClassCastException e) {
			return INVALID_POSITION;
		}
		final int childCount = tabContainer.getChildCount();
		for (int i = 0; i < childCount; i++) {
			if (tabContainer.getChildAt(i).equals(listItem)) {
				return i;
			}
		}

		return INVALID_POSITION;
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		try {
			int currentItem = mViewpager.getCurrentItem();
			mCurrentPosition = currentItem;
			mLastSelectTab = tabContainer.getChildAt(currentItem);
			if (mLastSelectTab instanceof TextView) {
				((TextView) mLastSelectTab).setTextColor(mSelectColor);
			}
		} catch (Exception e) {

		}
	}

	public int getCurrentPosition() {
		return mCurrentPosition;
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		if (mViewpager != null) {
			onTabSelect(mViewpager.getCurrentItem());
		}
	}

	public void setViewpager(ViewPager pager) {
		if (pager == null) {
			return;
		}
		this.mViewpager = pager;

		onTabSelect(pager.getCurrentItem());

		mViewpager.setOnPageChangeListener(new OnPageChangeListener() {
			private float destabWidth;
			private int desScrollX;

			@Override
			public void onPageSelected(int position) {
				mCurrentPosition = position;
				if (isClickTab) {
					if (mLastSelectTab instanceof TextView) {
						((TextView) mLastSelectTab).setTextColor(mDefaultColor);
					}
					View childAt = tabContainer.getChildAt(position);
					if (childAt instanceof TextView) {
						((TextView) childAt).setTextColor(mSelectColor);
					}
				}
				onTabSelect(position);
			}

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				if (isInit) {
					onTabSelect(position);
					isInit = false;
				}
				// TODO
				if (tabContainer.getChildCount() == 0) {
					return;
				}
				mPositionOffset = positionOffset;
				// 每次切换tab的时候锁定两个互相切换的tab的视图
				if (mCurScrollPosition != position) {
					mChild = tabContainer.getChildAt(position);
					if (position < tabContainer.getChildCount() - 1) {
						mNextChild = tabContainer.getChildAt(position + 1);
					}
					mCurScrollPosition = position;
				}

				LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mChild.getLayoutParams();
				int margin = params.leftMargin + params.rightMargin;
				if (position < tabContainer.getChildCount() - 1) {
					destabWidth = mNextChild.getWidth() * positionOffset + (1f - positionOffset) * mChild.getWidth();
				}
				float screenOffset = (getWidth() - destabWidth) / 2f;
				desScrollX = (int) (mChild.getLeft() - params.leftMargin - screenOffset);
				scrollTo((int) (desScrollX + (mChild.getWidth() + margin) * positionOffset), 0);
				invalidate();
			}

			@Override
			public void onPageScrollStateChanged(int state) {
				if (state == ViewPager.SCROLL_STATE_IDLE) {
					isClickTab = false;
					if (mLastSelectTab instanceof TextView) {
						((TextView) mLastSelectTab).setTextColor(mDefaultColor);
					}
					View childAt = tabContainer.getChildAt(mCurrentPosition);
					if (childAt instanceof TextView) {
						((TextView) childAt).setTextColor(mSelectColor);
						mLastSelectTab = childAt;
					}
				}
			}

		});

	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		final int height = getHeight();
		View currentTab = tabContainer.getChildAt(mCurScrollPosition);
		if (currentTab == null) {
			return;
		}
		float lineLeft = currentTab.getLeft();
		float lineRight = currentTab.getRight();

		if (mPositionOffset > 0f && mCurScrollPosition < tabContainer.getChildCount() - 1) {
			View nextTab = tabContainer.getChildAt(mCurScrollPosition + 1);
			// final float nextTabLeft = mNextChild.getLeft();
			// final float nextTabRight = mNextChild.getRight();
			final float nextTabLeft = nextTab.getLeft();
			final float nextTabRight = nextTab.getRight();
			lineLeft = (mPositionOffset * nextTabLeft + (1f - mPositionOffset) * lineLeft);
			lineRight = (mPositionOffset * nextTabRight + (1f - mPositionOffset) * lineRight);
			if (!isClickTab) {
				int color1 = evaluate(mPositionOffset, mSelectColor, mDefaultColor);
				int color2 = evaluate(mPositionOffset, mDefaultColor, mSelectColor);
				if (currentTab instanceof TextView) {
					((TextView) currentTab).setTextColor(color1);
				}
				if (nextTab instanceof TextView) {
					((TextView) nextTab).setTextColor(color2);
				}
			}
		}
		canvas.drawRect((int) lineLeft, height - mIndicatorHeight, (int) lineRight, height, mIndicatorPaint);

	}

	private Integer evaluate(float fraction, Object startValue, Integer endValue) {
		int startInt = (Integer) startValue;
		int startA = (startInt >> 24) & 0xff;
		int startR = (startInt >> 16) & 0xff;
		int startG = (startInt >> 8) & 0xff;
		int startB = startInt & 0xff;
		int endInt = endValue;
		int endA = (endInt >> 24) & 0xff;
		int endR = (endInt >> 16) & 0xff;
		int endG = (endInt >> 8) & 0xff;
		int endB = endInt & 0xff;
		return (startA + (int) (fraction * (endA - startA))) << 24 | (startR + (int) (fraction * (endR - startR))) << 16 | (startG + (int) (fraction * (endG - startG))) << 8
				| (startB + (int) (fraction * (endB - startB)));
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		mCacheWidth = 0;
		int cacheMargin = 0;
		int childCount = getChildCount();
		int width = MeasureSpec.getSize(widthMeasureSpec);
		// Log.e("", "onMeasure width:" + width + "  childCount:" + childCount);
		if (childCount == 0) {
			addView(tabContainer, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			childCount = getChildCount();
		}
		for (int i = 0; i < childCount; i++) {
			View childAt = getChildAt(i);
			int measuredWidth = childAt.getMeasuredWidth();
			if ((childAt instanceof LinearLayout) && childCount == 1) {
				if (tabContainer != childAt) {
					tabContainer = (LinearLayout) childAt;
				}
				int count = ((ViewGroup) childAt).getChildCount();

				for (int j = 0; j < count; j++) {
					View childAt2 = ((ViewGroup) childAt).getChildAt(j);
					LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) childAt2.getLayoutParams();
					int measuredWidth2 = childAt2.getMeasuredWidth();// +
					cacheMargin += params.leftMargin + params.rightMargin;
					mCacheWidth += measuredWidth2;
					// Log.e("", "cacheMargin:" + cacheMargin +
					// " ---  mCacheWidth:" + mCacheWidth);
				}
				// 超出的部分等于当前的宽度减去
				int over = width - mCacheWidth - cacheMargin;
				for (int j = 0; j < count; j++) {
					View child2 = ((ViewGroup) childAt).getChildAt(j);
					// over<0&&over>mCacheWidth

					if (over >= 0) {
						int eachMargin = (over) / count;
						LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child2.getLayoutParams();
						params.leftMargin += eachMargin / 2;
						params.rightMargin += eachMargin / 2;
						child2.setLayoutParams(params);
					} else if (over < 0 && width > mCacheWidth) {
						int eachMargin = (width - mCacheWidth) / count;
						LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child2.getLayoutParams();
						params.leftMargin = eachMargin / 2;
						params.rightMargin = eachMargin / 2;
						child2.setLayoutParams(params);
					} else {
						LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child2.getLayoutParams();
						params.width = LayoutParams.WRAP_CONTENT;
						params.leftMargin = 0;
						params.rightMargin = 0;
						child2.setLayoutParams(params);
					}
				}
			} else {
				mCacheWidth += measuredWidth;
				int over = width - mCacheWidth;
				if (over > 0) {
					int eachWidth = width / childCount;
					ViewGroup.LayoutParams params = childAt.getLayoutParams();
					params.width = eachWidth;
					childAt.setLayoutParams(params);
				} else {
					ViewGroup.LayoutParams params = childAt.getLayoutParams();
					params.width = LayoutParams.WRAP_CONTENT;
					childAt.setLayoutParams(params);
				}
			}
			int childWidthMeasureSpec = getChildMeasureSpec(MeasureSpec.UNSPECIFIED, 0, LayoutParams.WRAP_CONTENT);
			childAt.measure(childWidthMeasureSpec, heightMeasureSpec);
		}

	}

	@Override
	protected void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Log.e("", "onConfigurationChanged()");

		// requestLayout();
	}

}
